

package com.hazelcast.internal.networking.nio;

import com.hazelcast.internal.nio.IOUtil;
import org.junit.Assume;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.nio.channels.ServerSocketChannel;

public class NetworkTestUtil {

    private NetworkTestUtil() {
    }

    public static void assumeKeepAlivePerSocketOptionsNotSupported() throws Throwable {
        Assume.assumeFalse(socketSupportsKeepAliveOptions());
    }

    public static void assumeKeepAlivePerSocketOptionsSupported() throws Throwable {
        Assume.assumeTrue(socketSupportsKeepAliveOptions());
    }

    public static boolean socketSupportsKeepAliveOptions() throws Throwable {
        try (ServerSocketChannel serverSocketChannel = buildServerSocket()) {
            return IOUtil.supportsKeepAliveOptions(serverSocketChannel);
        }
    }

    private static ServerSocketChannel buildServerSocket() throws IOException {
        InetSocketAddress socketAddress = new InetSocketAddress("127.0.0.1", 0);
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        ServerSocket server = serverSocketChannel.socket();
        server.bind(socketAddress);
        return serverSocketChannel;
    }
}
